<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>二维码扫描</title>
    <script src="https://cdn.jsdelivr.net/npm/jsqr/dist/jsQR.js"></script>
    <script src="http://47.106.66.89:8080/js/vue.min.js"></script>
    <script src="http://47.106.66.89:8080/js/axios.min.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f5f5f5;
            margin: 0;
            padding: 20px;
        }
        h1 {
            color: #333;
        }
        #user-info, #token-info {
            background-color: #fff;
            padding: 10px;
            margin-bottom: 10px;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
        }
        #canvas {
            border: 1px solid #ccc;
            margin-bottom: 10px;
        }
        button {
            padding: 10px 20px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }
        button:hover {
            background-color: #45a049;
        }
    </style>
</head>
<body>
<div id="app">
    <div class="container">
        <form style="display: flex; flex-direction: column; width: 100px;">
            <label>用户名:</label><input id="name" type="text" v-model="name"><br>
            <label>密码:</label><input  id="pwd" type="password" v-model="pwd"><br>
            <button @click.prevent="login">登录</button>
        </form>
        <div>
            <h1>用户信息</h1>
            <div ref="userInfo" id="user-info">加载中...</div>
            <div id="token-info"></div>
        </div>
        <div>
            <input type="file" id="fileInput" accept="image/*">
        </div>
        <div>
            <textarea placeholder="Ctrl + Center 粘贴二维码" id="msg" v-model="text" @paste="psate"></textarea>
        </div>
        <div>
            <canvas ref="imageCode" id="canvas" hidden></canvas>
        </div>
        <div style="width: 50%; margin-left: auto; margin-right: auto;">
            <button id="confirm" hidden onclick="handleConfirm()">确认登录</button>
        </div>
    </div>
</div>

<script>
    var v = new Vue({
        el : "#app",
        data : {
            name: null,
            pwd: null,
            text: null,
            myinfo: null,
        },
        created() {
            // 添加请求拦截器
            axios.interceptors.request.use(function (config) {
                // 在发送请求之前做些什么
                var jwt = sessionStorage.getItem("jwt");
                if (jwt) {
                    config.headers.authorization = jwt;
                }
                return config;
            }, function (error) {
                // 对请求错误做些什么
                return Promise.reject(error);
            });

            // 添加响应拦截器
            axios.interceptors.response.use(function (response) {
                // 2xx 范围内的状态码都会触发该函数。
                // 对响应数据做点什么
                if (response.headers.authorization) {
                    sessionStorage.setItem("jwt", response.headers.authorization);
                }
                return response;
            }, function (error) {
                // 超出 2xx 范围的状态码都会触发该函数。
                // 对响应错误做点什么
                return Promise.reject(error);
            });

            axios.get("b-user/login/myinfo").then(res=> {
                if (res.data.code == 1) {
                    this.myinfo = res.data.data.user;
                    this.$emit("logined",this.myinfo);
                    this.$refs.userInfo.textContent = JSON.stringify(res.data.data, null, 2);
                    document.getElementById('fileInput').addEventListener('change', handleFileSelect, false);
                }
            });
        },
        methods : {
            login() {
                username = document.getElementById("name").value;
                pwd = document.getElementById("pwd").value;
                axios.get("b-user/mobile/login",{
                    params : {
                        username : username,
                        password : pwd
                    }
                }).then(res=> {
                    if (res.data.code == 1) {
                        this.myinfo = res.data.data.user;
                        document.getElementById('user-info').textContent = JSON.stringify(res.data.data, null, 2);
                    }
                });

                document.getElementById('fileInput').addEventListener('change', handleFileSelect, false);
            },
            psate(e){
                var clipboard = e.clipboardData;
                console.log(clipboard)
                if (clipboard.items[0].type.match(/image/)) {
                    let fd = new FormData();
                    let blob = clipboard.items[0].getAsFile();
                    let nm = "随机文件名.jpg"
                    fd.append("file",blob,nm);
                    fd.append("type", "image");
                    axios.post("upload/upload",fd).then(res=>{
                        if(res.data.code==1){
                            let webPath = res.data.data;
                            const img = new Image();
                            img.onload = function () {
                                const canvas = document.getElementById('canvas');
                                canvas.hidden = false;
                                const context = canvas.getContext('2d');
                                canvas.width = img.width;
                                canvas.height = img.height;
                                context.clearRect(0, 0, canvas.width, canvas.height);
                                context.drawImage(img, 0, 0, canvas.width, canvas.height);

                                const imageData = context.getImageData(0, 0, canvas.width, canvas.height);
                                const code = jsQR(imageData.data, imageData.width, imageData.height, {
                                    inversionAttempts: "dontInvert",
                                });

                                console.log("code", code)
                                if (code) {
                                    const uJson = JSON.parse(document.getElementById('user-info').textContent);
                                    fetch('http://127.0.0.1/b-user/mobile/scan?code=' + code.data + '&username=' + uJson.user.name + '&password=' + uJson.user.password + '&token=' + uJson.token, {
                                        method: 'GET',
                                        headers: {
                                            'Content-Type': 'application/json',
                                        }
                                    })
                                        .then(response => {
                                            // 检查响应状态码
                                            if (!response.ok) {
                                                throw new Error('网络响应不是ok状态');
                                            }
                                            return response.json(); // 解析JSON数据
                                        })
                                        .then(data => {
                                            // 在这里处理你的数据
                                            document.getElementById('token-info').textContent = data.code;
                                            const btn = document.getElementById('confirm');
                                            btn.hidden = false;
                                        })
                                        .catch(error => {
                                            // 在这里处理错误
                                            console.error('请求用户信息失败:', error);
                                            document.getElementById('user-info').textContent = '无法加载用户信息。';
                                        });
                                } else {
                                    console.info("未能识别到二维码，请确保图片清晰且完整。");
                                }
                            }
                            img.src = webPath;
                        }else{
                            this.$alter("文件上传失败!")
                        }
                    });
                }
            }
        }
    })
</script>

<script>


    function handleConfirm(event) {
      const uJson = JSON.parse(document.getElementById('user-info').textContent);
      const token = document.getElementById('token-info').textContent
      console.log(token)
      fetch('http://127.0.0.1/b-user/mobile/confirm?code=' + token + '&username=' + uJson.user.name + '&password=' + uJson.user.password+ '&token=' + uJson.token, {
                      method: 'GET',
                      headers: {
                        'Content-Type': 'application/json',
                      }
                    })
                    .then(response => {
                      // 检查响应状态码
                      if (!response.ok) {
                        throw new Error('网络响应不是ok状态');
                      }
                      alert("扫码登录成功")
                    })
                    .catch(error => {
                      // 在这里处理错误
                      console.error('请求用户信息失败:', error);
                      document.getElementById('user-info').textContent = '无法加载用户信息。';
                    });
    }

    function handleFileSelect() {
        const file = event.target.files[0];
        if (!file) {
            return;
        }

        const reader = new FileReader();
        reader.onload = function(fileEvent) {
            const img = new Image();
            img.onload = function(imgEvent) {
                const canvas = document.getElementById('canvas');
                canvas.hidden = false;
                const context = canvas.getContext('2d');
                canvas.width = img.width;
                canvas.height = img.height;
                context.clearRect(0, 0, canvas.width, canvas.height);
                context.drawImage(img, 0, 0, canvas.width, canvas.height);

                const imageData = context.getImageData(0, 0, canvas.width, canvas.height);
                const code = jsQR(imageData.data, imageData.width, imageData.height, {
                    inversionAttempts: "dontInvert",
                });

                console.log("code", code)
                console.log("uJson" + uJson)
                if (code) {
                    const uJson = JSON.parse(document.getElementById('user-info').textContent);
                    console.log("uJson" + uJson)
                    fetch('http://127.0.0.1/b-user/mobile/scan?code=' + code.data + '&username=' + uJson.user.name + '&password=' + uJson.user.password + '&token=' + uJson.token, {
                      method: 'GET',
                      headers: {
                        'Content-Type': 'application/json',
                      }
                    })
                    .then(response => {
                      // 检查响应状态码
                      if (!response.ok) {
                        throw new Error('网络响应不是ok状态');
                      }
                      return response.json(); // 解析JSON数据
                    })
                    .then(data => {
                      // 在这里处理你的数据
                      document.getElementById('token-info').textContent = data.code;
                      const btn = document.getElementById('confirm');
                      btn.hidden = false;
                    })
                    .catch(error => {
                      // 在这里处理错误
                      console.error('请求用户信息失败:', error);
                      document.getElementById('user-info').textContent = '无法加载用户信息。';
                    });
                } else {
                    console.info("未能识别到二维码，请确保图片清晰且完整。");
                }
            }
            img.src = fileEvent.target.result;
        };
        reader.readAsDataURL(file);
    }

</script>

</body>
</html>
